package com.reebake.ideal.security.access;

import com.reebake.ideal.security.entity.AuthUser;
import com.reebake.ideal.security.properties.ClientSecurityProperties;
import com.reebake.ideal.security.util.JwtAuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

@Slf4j
public final class BearerTokenAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private ClientSecurityProperties clientSecurityProperties;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        BearerTokenAuthenticationToken bearerTokenAuthentication = (BearerTokenAuthenticationToken) authentication;
        Object credentials = bearerTokenAuthentication.getCredentials();

        AuthUser principal = JwtAuthUtil.parse(credentials.toString(), clientSecurityProperties.getAccessTokenExpiredAhead());

        return new BearerTokenAuthenticationToken(principal, credentials, principal.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
